$(function () {
    //加载弹出层
    layui.use(['form','element','table'],
    function() {
        layer = layui.layer;
        element = layui.element;
        layui.table.on('sort(tableL)', function(obj){
          var dir = obj.type == "asc" ? "A" : "D";
          var Orders = dir + obj.field;

            layui.table.reload('tableL', {
               initSort: obj 
               ,where: { //请求参数
                 "Orders":Orders
               }
             });
        });

    });

    
    //退出事件
    loginOut();
    function loginOut(){
        var loBtn = $('#loginOut');
        var rData = {
            Command: "AdminExit"
        }
        loBtn.click(function(){
            var _this = this;
             reAjax( rData ,function(r){
                if( r.code == 0 ){
                   store.remove('user');
                   location.href = 'login.html';
                }
             });
             
             
        })
    }

    //触发事件
  var tab = {
        tabAdd: function(title,url,id){
          //新增一个Tab项
          element.tabAdd('xbs_tab', {
            title: title 
            ,content: '<iframe tab-id="'+id+'" frameborder="0" src="'+url+'" scrolling="yes" class="x-iframe"></iframe>'
            ,id: id
          })
        }
        ,tabDelete: function(othis){
          //删除指定Tab项
          element.tabDelete('xbs_tab', '44'); //删除：“商品管理”
          
          
          othis.addClass('layui-btn-disabled');
        }
        ,tabChange: function(id){
          //切换到指定Tab项
          element.tabChange('xbs_tab', id); //切换到：用户管理
        }
      };


   var  tableCheck = {
        init:function  () {
            $(".layui-form-checkbox").click(function(event) {
                if($(this).hasClass('layui-form-checked')){
                    $(this).removeClass('layui-form-checked');
                    if($(this).hasClass('header')){
                        $(".layui-form-checkbox").removeClass('layui-form-checked');
                    }
                }else{
                    $(this).addClass('layui-form-checked');
                    if($(this).hasClass('header')){
                        $(".layui-form-checkbox").addClass('layui-form-checked');
                    }
                }
                
            });

            if( $('#nav').length > 0 ) {
               logged(tab);
            }            
        },
        getData:function  () {
            var obj = $(".layui-form-checked").not('.header');
            var arr=[];
            obj.each(function(index, el) {
                arr.push(obj.eq(index).attr('data-id'));
            });
            return arr;
        }
    }

    //开启表格多选
    tableCheck.init();

      

    $('.container .left_open i').click(function(event) {
        if($('.left-nav').css('left')=='0px'){
            $('.left-nav').animate({left: '-221px'}, 100);
            $('.page-content').animate({left: '0px'}, 100);
            $('.page-content-bg').hide();
        }else{
            $('.left-nav').animate({left: '0px'}, 100);
            $('.page-content').animate({left: '221px'}, 100);
            if($(window).width()<768){
                $('.page-content-bg').show();
            }
        }

    });

  
    
    
})

/*弹出层*/
/*
    参数解释：
    title   标题
    url     请求的url
    id      需要操作的数据id
    w       弹出层宽度（缺省调默认值）
    h       弹出层高度（缺省调默认值）
*/
function x_admin_show(title,url,w,h){
    if (title == null || title == '') {
        title=false;
    };
    if (url == null || url == '') {
        url="404.html";
    };
    if (w == null || w == '') {
        w=($(window).width()*0.9);
    };
    if (h == null || h == '') {
        h=($(window).height() - 50);
    };
    return layer.open({
        type: 2,
        area: [w+'px', h +'px'],
        fix: false, //不固定
        maxmin: false,
        shadeClose: false,
        shade:0.4,
        title: title,
        content: url
    });
}

/*关闭弹出框口*/
function x_admin_close(){
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}


/*******传入html结构********/

function x_html( str,suFn,yesFn,H){
    //H = '500px' || H + 'px';
    hInit();
    function hInit(){
        if( $(window).height() < 600 ) {
             H = '350px';
        }else{
            H = '500px' || H + 'px';
        }
    }
    layer.open({
      title:'高级搜索',
      type: 1,
      skin: 'layui-layer-rim', //加上边框
      area: ['500px',H], //宽高
      content: str,
      btn:['确定'],
      success:function(){
          suFn && suFn();
      },
      yes: function(index, layero){
         yesFn && yesFn(index);
      }
    });
}
function x_html2( str,suFn,yesFn,H,w){
   hInit();
   function hInit(){
       if( $(window).height() < 600 ) {
            H = '350px';
       }else{
           H = '500px' || H + 'px';
       }
   }
   layer.open({
     title:'高级搜索',
     type: 1,
     skin: 'layui-layer-rim', //加上边框
     area: [w + 'px',H + 'px'], //宽高
     content: str,
     btn:['确定'],
     success:function(){
         suFn && suFn();
     },
     yes: function(index, layero){
        yesFn && yesFn(index);
     }
   });
}
function x_quConfirm( str,suFn,cancel,yesFn,H){
    //H = '500px' || H + 'px';
    hInit();
    function hInit(){
        if( $(window).height() < 600 ) {
             H = '350px';
        }else{
            H = '500px' || H + 'px';
        }
    }
    layer.open({
      title:'高级搜索',
      type: 1,
      skin: 'layui-layer-rim', //加上边框
      area: ['500px',H], //宽高
      content: str,
      btn:['审核通过','审核不通过'],
      success:function(){
          suFn && suFn();
      },
      btn2: function(index){
         cancel && cancel();
      },
      yes: function(index, layero){
         yesFn && yesFn(index);
      }
    });
}



//时间戳转为字符串格式
Date.prototype.format = function(format) {
       var date = {
              "M+": this.getMonth() + 1,
              "d+": this.getDate(),
              "h+": this.getHours(),
              "m+": this.getMinutes(),
              "s+": this.getSeconds(),
              "q+": Math.floor((this.getMonth() + 3) / 3),
              "S+": this.getMilliseconds()
       };
       if (/(y+)/i.test(format)) {
              format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
       }
       for (var k in date) {
              if (new RegExp("(" + k + ")").test(format)) {
                     format = format.replace(RegExp.$1, RegExp.$1.length == 1
                            ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
              }
       }
       return format;
}

//算往后推的时间
function backTime( dayNum ){
    var currDate = new Date();
    date = currDate.getDate();
    t = currDate.getTime() +  dayNum*24*60*60*1000;
    return new Date(t).format("yyyy-MM-dd");
}

//算出本周日期
function weekDate(date) {
  if(date){
    var now = new Date(date);
  }else{
    var now = new Date(); 
  }
  
  var nowTime = now.getTime() ; 
  var day = now.getDay();
  var oneDayLong = 24*60*60*1000 ; 

  var MondayTime = nowTime - (day-1)*oneDayLong  ; 
  var SundayTime =  nowTime + (7-day)*oneDayLong ; 


  var monday = new Date(MondayTime).format("yyyy-MM-dd");
  var sunday = new Date(SundayTime).format("yyyy-MM-dd");

  return {
      monday : monday,
      sunday : sunday
  }
}
/********* select **********/

function toSelect(){
   var yData = {
      Command : 'GetUnits'
   }
    reAjax(yData,function(res){
       var str = '';
       for( var i=0;i<res.length;i++){
          str += '<option value="'+res[i].Id+'">'+res[i].UnitName+'</option>';
       }
       $('#companyW').append( str );
    });
}


//多选选择
function muiltSelect(allData,fn){
  // var allData = {
  //     "[GT]InsertTime" : $('#start').val(),
  //     "[LT]InsertTime" : $('#end').val(),
  //     "[E]Department" : parseInt($('#buMen').val())
  // }
  for (var i in allData ){
     if( !allData[i] || allData[i] == 'undefined' || allData[i] == '' || allData[i] == '请选择' ){
       delete allData[i];
     }
  }
  fn && fn();
  // table.reload('tableL',{
  //   where: allData
  // });
}

/**********搜索重新渲染表格*************/
function reLoadTable(table,allData,wData){ //员工档案

   for (var i in allData ){
      if( !allData[i] || allData[i] == 'undefined' || allData[i] == '' || allData[i] == '请选择' ){
        delete allData[i];
      }
   }
   $.extend(allData, wData);
   renderTable(table,url,'#tableL',allData,headArr,function(res){
       var data = res.data;
       if( $('#menuBtn').length ) {
         hideMenu.length = 0;
         hideMenu.push('ContractNumber');
         hideMenu.push('WorkNumber','Ethnicity');
         hideMenu.push('Origin','Education');
         hideMenu.push('GraduateInstitutions');
         hideMenu.push('EmergencyContact','HomeAddress','IdIssuanceAuthority','SocialSecurityNumber');
         hideMenu.push('ProvidentFundNumber','Remark','ImportUserName','ImportDate');
         for( var k=0;k<hideMenu.length;k++) {
            $('[data-field='+hideMenu[k]+']').hide();
         }
       }

       for( i=0;i<data.length;i++){
          if( data[i].Sex == true ) {
             $('td[data-field="Sex"]').eq(i).find('div').text('男');
          }else{
             $('td[data-field="Sex"]').eq(i).find('div').text('女')
          }

          if( data[i].IsMarried == true ) {
             $('td[data-field="IsMarried"]').eq(i).find('div').text('已婚');
          }else{
             $('td[data-field="IsMarried"]').eq(i).find('div').text('未婚');
          }

       }
   })
}

/****************通用的重载表格*********************/
function comLoadTable(table,allData,wData,fn,seArr){

   for (var i in allData ){
      if( !allData[i] || allData[i] == 'undefined' || allData[i] == '' || allData[i] == '请选择' ){
        delete allData[i];
      }
   }
   $.extend(allData, wData);
   if(seArr){
      renderTable(table,url,'#tableL',allData,headArr,function(res){
          
          fn&&fn(res);
      },seArr);
   }else{
     renderTable(table,url,'#tableL',allData,headArr,function(res){
         fn&&fn(res);
     });
   }
  
}

/******************导出**************************/
$('#export').click(function(){
    var strArr = [];
    /*************身份证加空格*************/
    $('td[data-field="IdNumber"],td[data-field="IDNumbar"],td[data-field="BankCardNumber"]').each(function(i){
        var kg = '&nbsp;';
        //var nowStr = $(this).find('div').attr('style', 'mso-number-format:\@');
        var nowStr = $(this).find('div').html();
      
        strArr.push(nowStr);
        var str = kg + nowStr ;
        $(this).find('div').html( str );
    });
    HtmlExportToExcel('lay_table');
    //导出之后清空空格
    $('td[data-field="IdNumber"],td[data-field="IDNumbar"],td[data-field="BankCardNumber"]').each(function (i) {
        //var nowStr = $(this).find('div').attr('style', '');
        $(this).find('div').html(strArr[i]);
    });
});

function logged(tab) {
    // reAjax({ Command: "ReadAllAuthorizedMenus" }, function (result) {
    //     var treeMenus = { 0: { Items: [] } };
    //     $(result).each(function () {
    //         try {
    //             treeMenus[this.Id] = this;

    //             if (treeMenus[this.ParentId].Items) {
    //                 treeMenus[this.ParentId].Items.push(this);
    //             } else {
    //                 treeMenus[this.ParentId].Items = [this];
    //             }
    //         } catch (e) {
    //             console.error(this);
    //         }
    //     });

    //     var nav = $("#nav");
    //     //nav.html('');
    //     $(treeMenus[1530].Items).each(function (i) {
    //            var baseM = $("<li><a href=\"javascript:;\"><i class=\"iconfont\">&#xe6b8;</i><cite>" + this.Name + "</cite><i class=\"iconfont nav_right\">&#xe697;</i></a><ul class=\"sub-menu\"></ul></li>");

    //             var baseMUl = baseM.find("ul.sub-menu");

    //             $(this.Items).each(function () {
    //                 var pageM = $("<li><a _href=\"" + this.Url + "\"><i class=\"iconfont\">&#xe6a7;</i><cite>" + this.Name + "</cite></a></li>");

    //                 baseMUl.append(pageM);
    //             });
    //             nav.append(baseM);
    //     });
        
       
    // }).then(function () {
       
    // });

    $('.page-content-bg').click(function (event) {
        $('.left-nav').animate({ left: '-221px' }, 100);
        $('.page-content').animate({ left: '0px' }, 100);
        $(this).hide();
    });

    $('.layui-tab-close').click(function (event) {
        $('.layui-tab-title li').eq(0).find('i').remove();
    });

    //左侧菜单效果
    // $('#content').bind("click",function(event){
    $('.left-nav #nav li').click(function (event) {
        if ($(this).children('.sub-menu').length) {
            if ($(this).hasClass('open')) {
                $(this).removeClass('open');
                $(this).find('.nav_right').html('&#xe697;');
                $(this).children('.sub-menu').stop().slideUp();
                $(this).siblings().children('.sub-menu').slideUp();
            } else {
                $(this).addClass('open');
                $(this).children('a').find('.nav_right').html('&#xe6a6;');
                $(this).children('.sub-menu').stop().slideDown();
                $(this).siblings().children('.sub-menu').stop().slideUp();
                $(this).siblings().find('.nav_right').html('&#xe697;');
                $(this).siblings().removeClass('open');
            }
        } else {

            var url = $(this).children('a').attr('_href');
            var title = $(this).find('cite').html();
            var index = $('.left-nav #nav li').index($(this));

            for (var i = 0; i < $('.x-iframe').length; i++) {
                if ($('.x-iframe').eq(i).attr('tab-id') == index + 1) {
                    tab.tabChange(index + 1);
                    event.stopPropagation();
                    return;
                }
            };

            tab.tabAdd(title, url, index + 1);
            tab.tabChange(index + 1);
        }

        event.stopPropagation();

    });

    $('.sub-menu a').click(function () {
        var iframeLi = $('#iframeUl');
        $('.sub-menu a').css('color', '#333');
        $(this).css('color', 'rgb(20, 140, 241)');

        $('li', '#iframeUl').eq(0).find('i').click();
        $('li', '#iframeUl').each(function (i) {
            if (!$('li', '#iframeUl').eq(i).hasClass('layui-this')) {
                $('li', '#iframeUl').eq(i).find('i').click();
            }
        })
    });
}
